package org.jeecg.config.mybatis;

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

/**
 * 单数据源配置（jeecg.datasource.open = false时生效）
 * @Author zhoujf
 *
 */
@Configuration
@MapperScan(value={"org.jeecg.modules.**.mapper*"})
public class MybatisPlusConfig {

    /**
     * tenant_id 字段名
     */
    public static final String tenant_field = "tenant_id";

    /**
     * 有哪些表需要做多租户 这些表需要添加一个字段 ，字段名和tenant_field对应的值一样
     */
    private static final List<String> tenantTable = new ArrayList<String>();
    /**
     * ddl 关键字 判断不走多租户的sql过滤
     */
    private static final List<String> DDL_KEYWORD = new ArrayList<String>();
    private static final List<String> CREATOR_TABLE = new ArrayList<String>();

    static {
        tenantTable.add("jee_bug_danbiao");
        DDL_KEYWORD.add("alter");
        CREATOR_TABLE.add("question");
        CREATOR_TABLE.add("plan_effective");
        //CREATOR_TABLE.add("question_type");
        CREATOR_TABLE.add("plan");
        CREATOR_TABLE.add("trainee");
    }


    private LoginUser getLoginUser() {
        LoginUser sysUser = null;
        try {
            sysUser = SecurityUtils.getSubject().getPrincipal() != null ? (LoginUser) SecurityUtils.getSubject().getPrincipal() : null;
        } catch (Exception e) {
            //e.printStackTrace();
            sysUser = null;
        }
        return sysUser;
    }

    /**
     * 新多租户插件配置,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存万一出现问题
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new RankLineHandler(()->getLoginUser() ==null?null:getLoginUser().getUsername(),"create_by","coach")));
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new RankLineHandler(()->getLoginUser() ==null?null:getLoginUser().getOrgCode(),"sys_org_code","director")));
        // 如果用了分页插件注意先 add TenantLineInnerInterceptor 再 add PaginationInnerInterceptor
        // 用了分页插件必须设置 MybatisConfiguration#useDeprecatedExecutor = false
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }

       class RankLineHandler implements TenantLineHandler {
        String tenantIdColumn ;
        Supplier<String> tenantIdSupplier;
        String rank;
         RankLineHandler(Supplier<String> tenantIdSupplier, String tenantIdColumn, String rank){
             this.tenantIdSupplier =tenantIdSupplier;
             this.tenantIdColumn = tenantIdColumn;
             this.rank = rank;
         }

         @Override
         public String getTenantIdColumn() {
             return tenantIdColumn;
         }

         @Override
         public Expression getTenantId() {
             return  new StringValue(tenantIdSupplier.get());
         }

         @Override
         public boolean ignoreTable(String tableName) {
             if(!CREATOR_TABLE.contains(tableName)){
                 return true;
             }
             if(getLoginUser() == null){
                 return true;
             }
             if(!rank.equals(getLoginUser().getPost())){
                 return true;
             }
             return false;
         }
     }


    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }



//    /**
//     * mybatis-plus SQL执行效率插件【生产环境可以关闭】
//     */
//    @Bean
//    public PerformanceInterceptor performanceInterceptor() {
//        return new PerformanceInterceptor();
//    }

}
